package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjWorkStatementTemplateFieldMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkStatementTemplateFieldContentService;
import com.zb.service.ZjWorkStatementTemplateFieldService;
import com.zb.service.ZjWorkStatementTemplateService;
import com.zb.vo.WorkFieldContentVo;
import com.zb.vo.WorkStatementTemplateFieldVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单结单模板字段表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-07
 */
@Service
public class ZjWorkStatementTemplateFieldServiceImpl extends ServiceImpl<ZjWorkStatementTemplateFieldMapper, ZjWorkStatementTemplateField> implements ZjWorkStatementTemplateFieldService {
    @Resource
    private ZjWorkStatementTemplateFieldMapper workStatementTemplateFieldMapper;
    @Resource
    private ZjWorkStatementTemplateFieldContentService workStatementTemplateFieldContentService;
    @Resource
    private ZjWorkStatementTemplateService workStatementTemplateService;

    // 新增、修改、删除结单模板字段
    @Override
    public void save(Long custAccId, Long workStatementTemplateId, List<WorkStatementTemplateFieldVo> templateField) {
        if (null == templateField || templateField.isEmpty()) {
            return;
        }
        Assert.isTrue(templateField.size() <= 20, "结单模板自定义字段最多允许添加 20 个");
        Assert.isTrue(
                templateField.stream().map(WorkStatementTemplateFieldVo::getName).toList().size() == templateField.stream().map(WorkStatementTemplateFieldVo::getName).collect(Collectors.toSet()).size(),
                "结单模板自定义字段名称重复");
        List<ZjWorkStatementTemplateField> adds = new ArrayList<>();
        List<ZjWorkStatementTemplateField> updates = new ArrayList<>();
        ZjWorkStatementTemplateField field = null;
        List<ZjWorkStatementTemplateFieldContent> conAdds = new ArrayList<>();
        List<ZjWorkStatementTemplateFieldContent> conUpdates = new ArrayList<>();
        ZjWorkStatementTemplateFieldContent fieldContent = null;
        List<Long> delFieldContentIds = new ArrayList<>();
        for (WorkStatementTemplateFieldVo vo : templateField) {
            field = new ZjWorkStatementTemplateField();
            BeanUtil.copyProperties(vo, field);
            field.setDisabled(vo.getStatus());
            if (null != field.getId()) {
                updates.add(field);
            } else {
                field.setId(IdWorker.getId());
                field.setCustAccId(custAccId);
                field.setWorkStatementTemplateId(workStatementTemplateId);
                adds.add(field);
            }
            if (CollectionUtils.isNotEmpty(vo.getDelContentIds())) {
                delFieldContentIds.addAll(vo.getDelContentIds());
            }
            for (WorkFieldContentVo k : vo.getContentVos()) {
                fieldContent = new ZjWorkStatementTemplateFieldContent();
                BeanUtil.copyProperties(k, fieldContent);
                if (null != k.getId()) {
                    conUpdates.add(fieldContent);
                    continue;
                }
                fieldContent.setId(IdWorker.getId());
                fieldContent.setCustAccId(custAccId);
                fieldContent.setWorkStatementTemplateFieldId(field.getId());
                conAdds.add(fieldContent);
            }
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
        if (!conAdds.isEmpty()) workStatementTemplateFieldContentService.saveBatch(conAdds);
        if (!conUpdates.isEmpty()) workStatementTemplateFieldContentService.updateBatchById(conUpdates);
        if (!delFieldContentIds.isEmpty()) workStatementTemplateFieldContentService.removeByIds(delFieldContentIds);
    }

    // 根据结单模板ID获取模板字段
    @Override
    public List<WorkStatementTemplateFieldVo> getByworkStatementTemplateId(Long workStatementTemplateId) {
        QueryWrapper<ZjWorkStatementTemplateField> wrapper = new QueryWrapper<>();
        wrapper.eq("work_statement_template_id", workStatementTemplateId);
        List<ZjWorkStatementTemplateField> templateFieldList = this.list(wrapper);

        List<Long> ids = templateFieldList.stream().map(ZjWorkStatementTemplateField::getId).toList();
        List<ZjWorkStatementTemplateFieldContent> contentList = workStatementTemplateFieldContentService.getByWorkStatementTemplateFieldIds(ids);
        return templateFieldList.stream().map(k -> {
            WorkStatementTemplateFieldVo vo = new WorkStatementTemplateFieldVo();
            BeanUtil.copyProperties(k, vo);
            vo.setStatus(k.getDisabled());
            vo.setContentVos(contentList.stream().filter(f -> Objects.equals(f.getWorkStatementTemplateFieldId(), k.getId())).map(content -> {
                WorkFieldContentVo con = new WorkFieldContentVo();
                BeanUtil.copyProperties(content, con);
                return con;
            }).toList());
            return vo;
        }).toList();
    }

    // 根据字段ID获取结单字段详情
    @Override
    public WorkStatementTemplateFieldVo getFieldDetail(Long id) {
        ZjWorkStatementTemplateField templateField = this.getById(id);
        Assert.isTrue(null != templateField, "结单字段ID参数[" + id + "]的数据不存在");

        WorkStatementTemplateFieldVo vo = new WorkStatementTemplateFieldVo();
        BeanUtil.copyProperties(templateField, vo);
        vo.setStatus(templateField.getDisabled());
        vo.setContentVos(workStatementTemplateFieldContentService.getByWorkStatementTemplateFieldId(id).stream().map(content -> {
            WorkFieldContentVo con = new WorkFieldContentVo();
            BeanUtil.copyProperties(content, con);
            return con;
        }).toList());
        return vo;
    }

    // 根据结单模板ID删除
    @Override
    public void deleteBatchByWorkStatementTemplateIds(List<Long> workStatementTemplateIds) {
        if (null == workStatementTemplateIds || workStatementTemplateIds.isEmpty()) {
            return;
        }
        List<ZjWorkStatementTemplateField> templateFieldList = getByworkStatementTemplateIds(workStatementTemplateIds);
        List<Long> ids = templateFieldList.stream().map(ZjWorkStatementTemplateField::getId).toList();
        workStatementTemplateFieldContentService.dleteBatchByWorkStatementTemplateFieldIds(ids);
        this.removeByIds(ids);
    }

    // 根据模板ID集合获取模板字段信息
    @Override
    public List<ZjWorkStatementTemplateField> getByworkStatementTemplateIds(List<Long> workStatementTemplateIds) {
        if (CollectionUtil.isEmpty(workStatementTemplateIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkStatementTemplateField> wrapper = new QueryWrapper<>();
        wrapper.in("work_statement_template_id", workStatementTemplateIds);
        return this.list(wrapper);
    }

    // 根据模板字段ID获取关联的模板字段信息
    @Override
    public List<ZjWorkStatementTemplateField> getRelationByIds(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return new ArrayList<>();
        }
        // todo 查询存在关联的模板信息
        return new ArrayList<>();
    }

    // 批量启用或禁用结单模板字段
    @Override
    public void updateDisableBatchById(List<Long> ids, boolean status) {
        workStatementTemplateFieldMapper.updateDisableBatchById(ids, status);
    }

    // 批量删除结单模板字段
    @Override
    public void deleteBatchById(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return;
        }
        List<ZjWorkStatementTemplateField> relation = getRelationByIds(ids);
        if (!relation.isEmpty()) {
            Assert.isTrue(false, "结单字段[" + relation.stream().map(ZjWorkStatementTemplateField::getName).collect(Collectors.joining("、")) + "]已被使用中，不可删除");
        }
        workStatementTemplateFieldContentService.dleteBatchByWorkStatementTemplateFieldIds(ids);
        this.removeByIds(ids);
    }

    // 获取导出的结单字段
    @Override
    public List<ExportFieldAttrVo> getStatementTemlateField(Long custAccId) {
        // 结单模板
        QueryWrapper<ZjWorkStatementTemplate> templateQueryWrapper = new QueryWrapper<>();
        templateQueryWrapper.select("id", "name")
                .eq("cust_acc_id", custAccId);
        List<ZjWorkStatementTemplate> templateList = workStatementTemplateService.list(templateQueryWrapper);
        if (CollectionUtil.isEmpty(templateList)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkStatementTemplateField> templateFieldQueryWrapper = new QueryWrapper<>();
        templateFieldQueryWrapper.select("id", "work_statement_template_id", "name")
                .in("type", 1, 2, 3, 4, 8)
                .eq("cust_acc_id", custAccId);
        List<ZjWorkStatementTemplateField> templateFieldList = this.list(templateFieldQueryWrapper);
        List<ExportFieldAttrVo> fieldAttrVos = new ArrayList<>();
        ExportFieldAttrVo fieldAttrVo = null;
        for (ZjWorkStatementTemplateField field : templateFieldList) {
            fieldAttrVo = new ExportFieldAttrVo();
            fieldAttrVo.setType(3);
            fieldAttrVo.setValue(field.getId().toString());
            fieldAttrVo.setName("[" + templateList.stream().filter(f -> Objects.equals(f.getId(), field.getWorkStatementTemplateId())).findFirst().map(ZjWorkStatementTemplate::getName).orElse("") + "]" + field.getName());
            fieldAttrVos.add(fieldAttrVo);
        }
        return fieldAttrVos;
    }

}
